<template>
  <main-content title="订单详情" back>
    <div v-loading="loading">
      <section
        v-if="orderData?.status !== 6"
        class="steps-line"
      >
        <simple-steps
          :active-index="activityValue"
          :steps="steps"
        />
      </section>

      <section class="status-line">
        <div class="left">
          <div class="status">
            <div class="status-main">
              <div class="icon">
                <el-icon><Warning /></el-icon>
              </div>
              当前订单状态：
              <span style="font-size: 22px; font-weight: bold">{{ getOrderStatus(orderData?.status) }}</span>
            </div>
            <div
              v-if="orderData?.errMsg"
              class="status-sub"
            >
              {{ orderData?.errMsg }}
            </div>
          </div>
        </div>
        <div class="right">
          <el-button
            type="default"
            @click="openExternal(orderData?.externalRequestRecordBos)"
          >
            查看供应商日志
          </el-button>
          <el-button @click="fillLogisticsInfo('setRemarkDialogVisible')">
            备注订单
          </el-button>
        </div>
      </section>

      <section class="table-section">
        <div class="table-title">
          <div class="decorator"></div>
          基本信息
        </div>
        <div class="table-wrapper">
          <el-table :data="basicTableData" style="width: 100%">
            <el-table-column prop="orderNo" label="订单号" width="180" />
            <el-table-column prop="insName" label="所属机构" />
            <!-- <el-table-column prop="businessType" label="订单来源" /> -->
            <el-table-column
              label="用户ID"
              prop="userId"
            />
            <el-table-column
              label="客户唯一标识"
              prop="unionId"
            />
            <el-table-column
              v-if="orderData?.goodsType === 'real'"
              label="配送方式"
              prop="ext"
            >
              <template #default="scope">
                <div>{{ scope.row?.ext?.logisticsCompany ?? '' }}</div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="orderData?.goodsType === 'real'"
              prop="logisticsNum"
              label="物流单号"
            >
              <template #default="scope">
                <div>{{ scope.row?.ext?.logisticsNum ?? '' }}</div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </section>

      <section class="table-section">
        <div class="table-title">
          <div class="decorator"></div>
          领取信息
        </div>
        <div class="table-wrapper">
          <el-table :data="basicTableData" style="width: 100%">
            <!-- 实物 -->
            <template v-if="orderData.goodsType == 'real'">
              <el-table-column prop="receiveUserName" label="收货人">
                <template #default="scope">
                  <div>
                    {{ scope.row.ext?.receiveUserName ?? '' }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="receiveUserPhone" label="手机号码">
                <template #default="scope">
                  <div>
                    {{ scope.row.ext?.receiveUserPhone ?? '' }}
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="receivePostalCode" label="邮政编码">
                <template #default="scope">
                  <div>
                    {{ scope.row.ext?.receivePostalCode ?? '' }}
                  </div>
                </template>
              </el-table-column> -->
              <el-table-column prop="receiveAddress" label="收货地址">
                <template #default="scope">
                  <div>
                    {{ scope.row.ext?.receiveAddress ?? '' }}
                  </div>
                </template>
              </el-table-column>
            </template>
            <!-- 充值 -->
            <template v-if="orderData.goodsType == 'recharge'">
              <el-table-column prop="rechargeAccount" label="充值账号">
                <template #default="scope">
                  <div>
                    {{ scope.row.ext?.rechargeAccount ?? '' }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="rechargeAccount"
                label="到账时间"
              >
                <template #default="scope">
                  <div>
                    {{ setOrderTime(scope.row.finishTime) }}
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column label="充值时间">
                <template #default="scope">
                  <div>
                    {{ setOrderTime(scope.row.payTime) }}
                  </div>
                </template>
              </el-table-column> -->
              <!-- <el-table-column label="供应商流水号">
                <template #default="scope">
                  <el-button link type="primary" v-if="scope.row.externalRequestRecordBos"
                    @click="openExternal(scope.row.externalRequestRecordBos)">查看详情</el-button>
                </template>
              </el-table-column> -->
            </template>
            <!-- 卡密 -->
            <template v-if="orderData.goodsType == 'cardPassword'">
              <el-table-column
                prop="cardPassword"
                label="卡号/卡密"
              >
                <template #default="scope">
                  <div>
                    {{ scope.row.ext?.cardNo ?? '' }} / {{ aeseData(scope.row.ext?.cardPassword ?? '') }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="领取时间">
                <template #default="scope">
                  <div>
                    {{ setOrderTime(scope.row?.finishTime) }}
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column label="供应商流水号">
                <template #default="scope">
                  <el-button link type="primary" v-if="scope.row.externalRequestRecordBos"
                    @click="openExternal(scope.row.externalRequestRecordBos)">查看详情</el-button>
                </template>
              </el-table-column> -->
            </template>
            <!-- 代币 -->
            <template v-if="orderData.goodsType == 'currency'">
              <el-table-column prop="currencyName" label="代币名称">
                <template #default="scope">
                  <div>
                    {{ scope.row.currencyName ?? '' }}
                  </div>
                </template>
              </el-table-column>

              <!-- <el-table-column prop="goodsNum" label="商品数量" >
                <template #default="scope">
                  <div>
                     {{scope.row.ext?.goodsNum ?? ''}}
                  </div>
                </template>
              </el-table-column> -->
            </template>
          </el-table>
        </div>
      </section>

      <section class="table-section">
        <div class="table-title">
          <div class="decorator"></div>
          商品信息
        </div>
        <div class="table-wrapper">
          <el-table :data="basicTableData" style="width: 100%">
            <el-table-column prop="thumbnailUrl" label="商品图片" width="180">
              <template #default="scope">
                <div>
                  <el-avatar style="margin-top: 8px;" shape="square" :size="80" fit="fill"
                    :src="scope.row.thumbnailUrl" />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="商品名称" />
            <el-table-column prop="productName" label="规格名称" />
            <el-table-column
              prop="payOfMoney"
              label="价格"
            >
              <template #default="props">
                <div>
                  {{ getPointsAndMoneyString(props.row) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="goodsNum" label="数量" />
            <el-table-column label="合计">
              <template #default="props">
                {{ getPointsAndMoneyString(props.row) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </section>
    </div>
  </main-content>
  <SetRemark v-model:show="dialogData.setRemarkDialogVisible" @refresh="refresh" :order-data="orderData"></SetRemark>
  <!-- 供应商日志 -->
  <el-dialog v-model="externalRequestShow" title="供应商日志" @close="externalRequestShow = false">
    <div style="padding-bottom:16px;">order_number 为供应商流水号</div>
    <el-table :data="externalRequestData" style="width: 100%" height="600">
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column label="请求时间" min-width="140">
        <template #default="scope"> {{ formatTime(scope.row.createTime) }}</template>
      </el-table-column>
      <el-table-column label="请求状态" min-width="100">
        <template #default="scope"> {{ scope.row.callbackStatus ?? scope.row.status ?? '' }}</template>
      </el-table-column>
      <el-table-column property="request" label="请求参数" min-width="220" />
      <el-table-column property="response" label="返回结果" min-width="200">
        <template #default="{ row }">
          {{ row.callbackResponse ? JSON.stringify(row.callbackResponse) : row.response ? JSON.stringify(row.response) :
            '' }}
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>

<script setup lang="ts">
import type { Ref } from "vue";
import type { IOrderDetailData, IOrderDetail, IExternalRequestRecordBosItem } from "@/api/modules/pointsMall";
import moment from "moment";
import { Warning } from "@element-plus/icons-vue";
import { getOrderDetail } from "@/api/pointsMall";
import { orderStatus } from "@/config/dictionary";
import { dateFormat } from "@/utils/filters";
import { getPointsAndMoneyString } from "@/utils";
import { useMallConfig } from "@/views/pointsMall/compositions/useMallConfig";
import SetRemark from "./components/SetRemark.vue";


//加密卡密类
const aeseData = (val: string) => {
  if (val) {
    let str = JSON.stringify(val).replaceAll(/"/g, "").slice(0, -4)
    return `${str}####`
  }
  return ""
}

const { mallConfig } = useMallConfig();
const Route = useRoute();
const orderData = ref({} as any)

const externalRequestData:Ref<IExternalRequestRecordBosItem[]> = ref([])
const externalRequestShow = ref(false)
const openExternal = (rows: IExternalRequestRecordBosItem[] | null | undefined) => {
  externalRequestData.value = rows ?? []
  externalRequestShow.value = true
}
const formatTime = (value: string) => {
  if (value) {
    return moment(value).format("YYYY.MM.DD HH:mm:ss");
  }
};


const basicTableData = computed(() => {
  return [
    {
      ...orderData.value,
      unionId: orderData.value?.user?.unionId,
      userId: orderData.value?.user?.id,
    }
  ]
})

const loading = ref(false)
const activityValue = ref(1)

const dialogData = reactive({
  setRemarkDialogVisible: false,
})


const fillLogisticsInfo = (type: string) => {
  dialogData[type] = true
}

// 设置订单状态
const getOrderStatus = (status: number) => {
  return orderStatus.find(item => item.value === status)?.label ?? '--'
}

const setOrderTime = (time: any) => {
  if (time) {
    return dateFormat(time)
  }
  return ''
}

const setActivity = () => {
  if (orderData.value.status == 1 || orderData.value.status == 2) {
    activityValue.value = 2
  } else if (orderData.value.status == 3 || orderData.value.status == 4) {
    activityValue.value = 3
  } else if (orderData.value.status == 5 || orderData.value.status == 6) {
    activityValue.value = 4
  }
  // activityValue.value = 3
}
const getOrderDetailData = async () => {
  loading.value = true
  let params = {
    businessType: 'activity',
    id: <string>Route.query.id
  }
  let rs: any = await getOrderDetail(params)
  if (rs.code === 200) {
    console.log('[ rs ]', rs)
    orderData.value = rs.payload
    setActivity()
    // basicTableData = rs.payload
  }

  loading.value = false
  getSteps()
}

const steps:Ref<{title: string; description?: string}[]> = ref([])
const getSteps = () => {
  const _steps = []
  _steps.push({
    title: '提交订单',
    description: setOrderTime(orderData.value?.createTime),
    status: [ 1 ],
  })

  _steps.push({
    title: '用户支付',
    description: setOrderTime(orderData.value?.payTime),
    status: [ 0 ]
  })

  if (orderData.value?.verifyStep) {
    _steps.push({
      title: '审核订单',
      description: setOrderTime(orderData.value?.auditTime),
      status: [ 11 ]
    })
  }

  if (orderData.value?.goodsType !== 'real') {
    _steps.push({
      title: '用户提货',
      description: setOrderTime(orderData.value?.pickUpTime),
      status: [ 2, 7 ],
    })
  }

  if (orderData.value?.goodsType !== 'real') {
    _steps.push({
      title: '商品提货中',
      description: setOrderTime(orderData.value?.pickUpTime),
      status: [ 8 ]
    })
  }

  if (orderData.value?.goodsType === 'real') {
    _steps.push({
      title: '商家发货',
      description: setOrderTime(orderData.value.ext?.storeShipTime),
      status: [ 3, 9, 10 ]
    })
  }

  if (orderData.value?.goodsType === 'real') {
    _steps.push({
      title: '用户确认收货',
      description: setOrderTime(orderData.value.ext?.storeShipTime),
      status: [ 4 ],
    })
  }

  _steps.push({
    title: '订单完成',
    description: setOrderTime(orderData.value?.finishTime),
    status: [ 5 ]
  })

  activityValue.value = _steps.findIndex( item => item.status.includes(orderData.value?.status ?? -1))
  steps.value = _steps;
}

const refresh = () => {
  getOrderDetailData()
}

onBeforeMount(async () => {
  await getOrderDetailData()
})
</script>

<style scoped lang="scss">
.text-show {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.steps-line {
  padding: 20px;
  background: #F8F8F8;
}

.status-line {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 0;

  .left {
    display: flex;
    align-items: center;

    .status {
      margin-left: 10px;

      .status-main {
        font-size: 16px;
        line-height: 16px;
        display: flex;
        align-items: center;

        .icon {
          font-size: 18px;
          display: flex;
          align-items: center;
          color: var(--el-color-primary);
          margin-right: 10px;
        }
      }

      .status-sub {
        font-size: 14px;
        line-height: 14px;
        color: #999;
        margin-top: 10px;
        margin-left: 28px;
      }
    }
  }
}

.table-section {
  margin-top: 20px;

  .table-title {

    display: flex;
    align-items: center;

    .decorator {
      width: 3px;
      height: 15px;
      margin-right: 10px;
      background: var(--el-color-primary-light-3);
    }
  }

  .table-wrapper {
    margin-top: 10px;
  }
}
</style>
